﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace NKestrelClient.FaultTolerance
{
    public class Retry
    {
        public static void OnFail(RetryAction action, int maxRepeats, IDelayStrategy delay)
        {
            OnFail(action, maxRepeats, delay, e => {throw e;});
        }

        public static void OnFail(RetryAction action, int maxRepeats, IDelayStrategy delay, Action<Exception> onError)
        {
            int currentTry = 1;
            while (true)
            {
                try
                {
                    action(currentTry, delegate(int x) { currentTry = x; });
                    return;
                }
                catch (Exception e)
                {
                    if (currentTry == maxRepeats)
                    {
                        onError(e);
                        return;
                    }
                    currentTry++;
                }
                Thread.Sleep(delay.GetDelay(currentTry, maxRepeats));
            }
        }
    }
}
